package yja.gzw.app.activity

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.IntegerRes
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.CityBean
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.citywheel.CityConfig
import com.lljjcoder.style.citypickerview.CityPickerView
import com.shixia.colorpickerview.ColorPickerView
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityBianjiagerengBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.File
import java.util.Calendar


class BianjiagerengActivity :BaseActivity<Mainviewmodel, ActivityBianjiagerengBinding>(R.layout.activity_bianjiagereng){
    var yansezhi=0
    private lateinit var bottomSheetDialog: BottomSheetDialog
    var file: File?=null
    var mPicker: CityPickerView = CityPickerView()
    fun tanchuanfg(views: TextView){

        bottomSheetDialog = BottomSheetDialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_shurukuang, null)
        bottomSheetDialog.setContentView(view)
        val shurukuang= view.findViewById<EditText>(R.id.shurukuang)
        val quxiao= view.findViewById<TextView>(R.id.quxiao)
        val queding= view.findViewById<TextView>(R.id.queding)
        val chacha= view.findViewById<ImageView>(R.id.chacha)


        chacha.setOnClickListener {
            bottomSheetDialog.dismiss()

        }

        queding.setOnClickListener {
            views.text=shurukuang.text.toString()

            if(views == binding.yonghumingchneg){

                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("nickname" to shurukuang.text.toString()))
            }else if(views == binding.qianming){
                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("bio" to shurukuang.text.toString()))

            }else if(views == binding.xuexiao){
                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("school" to shurukuang.text.toString()))
            }



            bottomSheetDialog.dismiss()
        }

        quxiao.setOnClickListener {
            bottomSheetDialog.dismiss()
        }

        bottomSheetDialog.show()

    }
    private fun showDatePickerDialog() {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog(
            this,
            { _, selectedYear, selectedMonth, selectedDayOfMonth ->
                val selectedDate = String.format("%d-%02d-%02d", selectedYear, selectedMonth + 1, selectedDayOfMonth)

                binding.shengri.text=selectedDate
                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("birthday" to selectedDate))

            },
            year,
            month,
            day
        )
        datePickerDialog.show()
    }

    private fun chengshixuanzeqi(){

        //添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        val cityConfig = CityConfig.Builder().build()
        mPicker.setConfig(cityConfig)
        mPicker.setOnCityItemClickListener(object : OnCityItemClickListener() {
            override fun onSelected(
                province: ProvinceBean?,
                city: CityBean?,
                district: DistrictBean?
            ) {
                //省份province
                //城市city
                //地区district
                binding.chengshi.text=""+province+city+district

                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("city" to ""+province+city+district))
            }

            override fun onCancel() {
                Toast.makeText(this@BianjiagerengActivity, "已取消", Toast.LENGTH_SHORT).show()
            }
        })

        mPicker.showCityPicker()
        //显示



    }

    override fun initView() {

        binding.fanhui.setOnClickListener {
            finish()
        }

        viewmodel.onwodezhuyewang(UserData.token, mapOf("" to ""))



        binding.yanseanniu.setOnClickListener {

            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_yanse, null)
            bottomSheetDialog.setContentView(view)
            val queding= view.findViewById<TextView>(R.id.queding)
            val quxiao= view.findViewById<TextView>(R.id.quxiao)
            val chacha= view.findViewById<ImageView>(R.id.chacha)
            val cpvcolor= view.findViewById<ColorPickerView>(R.id.cpv_color)

            chacha.setOnClickListener {
                bottomSheetDialog.dismiss()
            }

            quxiao.setOnClickListener {
                bottomSheetDialog.dismiss()
            }
            cpvcolor.setOnColorChangeListener { color ->
                yansezhi=color
            }

            queding.setOnClickListener {


                viewmodel.onxiugaiziliaowang(UserData.token,mapOf("nickname_color" to yansezhi.toString()))

                binding.yanse.setTextColor(yansezhi)


                bottomSheetDialog.dismiss()

            }


            bottomSheetDialog.show()


        }

        binding.xingbieanniu.setOnClickListener {
            bottomSheetDialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_xingbie, null)
            bottomSheetDialog.setContentView(view)
            val xing1= view.findViewById<RadioButton>(R.id.xing1)
            val xing2= view.findViewById<RadioButton>(R.id.xing2)
            val queding= view.findViewById<TextView>(R.id.queding)
            val quxiao= view.findViewById<TextView>(R.id.quxiao)
            val chacha= view.findViewById<ImageView>(R.id.chacha)

            chacha.setOnClickListener {
                bottomSheetDialog.dismiss()
            }
            quxiao.setOnClickListener {
                bottomSheetDialog.dismiss()

            }
            queding.setOnClickListener {
                //todo 性别
                if(xing1.isChecked){
                    viewmodel.onxiugaiziliaowang(UserData.token,mapOf("gender" to "0"))
                    binding.xinbie.text="男"
                }else{
                    viewmodel.onxiugaiziliaowang(UserData.token,mapOf("gender" to "1"))
                    binding.xinbie.text="女"
                }
                bottomSheetDialog.dismiss()
            }


            bottomSheetDialog.show()

        }


        mPicker.init(this);
        binding.chengshianniu.setOnClickListener {
            chengshixuanzeqi()

        }
        binding.shengrianiu.setOnClickListener {
            showDatePickerDialog()
        }
        binding.nichangdianji.setOnClickListener {
            tanchuanfg(binding.yonghumingchneg)
        }

        binding.qianminganiu.setOnClickListener {
            tanchuanfg(binding.qianming)
        }

        binding.xuexiaoanniu.setOnClickListener {
            tanchuanfg(binding.xuexiao)
        }


        binding.touxiang.setOnClickListener {

            openGallery()

        }
    }
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                file = File(getRealPathFromURI(uri))

                val requestFile = file?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val body = MultipartBody.Part.createFormData("file", file?.name,requestFile!!)
                viewmodel.onluying(body)
            }
        }
    }
    private fun getRealPathFromURI(contentUri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(contentUri, projection, null, null, null)
        val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val result = cursor?.getString(column_index!!)
        cursor?.close()
        return result!!
    }

    override fun dataObservese() {
        viewmodel.onwodezhuye.observe(this, Observer {
                if(it.code==1){
                    val requestOptions = RequestOptions.bitmapTransform(CircleCrop())
                    Glide.with(this).load("http://117ai.32.hzgqapp.com/"+it.data.avatar)
                        .apply(requestOptions)
                        .into(binding.touxiang)

                    binding.yonghumingchneg.text=it.data.nickname
                  val zhi=Integer.parseInt( it.data.nickname_color.toString())
                    binding.yanse.setTextColor(zhi)
                    binding.qianming.text=it.data.bio
                    if(it.data.gender==0){
                        binding.xinbie.text="男"

                    }else{
                        binding.xinbie.text="女"
                    }
                    binding.shengri.text=it.data.birthday.toString()
                    binding.chengshi.text=it.data.city.toString()
                    binding.xuexiao.text=it.data.school.toString()

                }else{
                    Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()

                }


        })

        viewmodel.onxiugaiziliao.observe(this, Observer {
            if(it.code==1){
                Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show()
              //  finish()
            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })

        viewmodel.onlusc.observe(this, Observer {
            if(it.code==1){




                Log.e("上传图片的半路径",it.data.url)

                val requestOptions = RequestOptions.bitmapTransform(CircleCrop())
               Glide.with(this).load("http://117ai.32.hzgqapp.com/"+it.data.url)
                   .apply(requestOptions)
                   .into(binding.touxiang)

            viewmodel.onxiugaiziliaowang(UserData.token,mapOf("avatar" to it.data.url))



            }


        })



    }
    companion object {
        private const val GALLERY_REQUEST_CODE = 1001
    }
}